package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"rbac/cache"
	"rbac/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	car_num := c.PostForm("car_num")
	car := models.Car{
		Model:   gorm.Model{},
		CarCode: car_code,
		CarName: car_name,
		CarNum:  car_num,
	}
	err := models.DB.Create(&car).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "车辆添加失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "车辆添加成功",
			"data": car,
		})
		return
	}
}
func OrderAdd(c *gin.Context) {
	order_no := c.PostForm("order_no")
	from_address := c.PostForm("from_address")
	to_address := c.PostForm("to_address")
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	order := models.Order{
		OrderNo:     order_no,
		FromAddress: from_address,
		ToAddress:   to_address,
		Cid:         cid,
	}
	err := models.DB.Create(&order).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "订单添加失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "订单添加成功",
		"data": order,
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var orders []models.OrderList
	list_key := "list_key" + strconv.Itoa(page)
	cachejson, _ := cache.Rdb.Get(cache.Ctx, list_key).Result()
	if cachejson == "" {
		models.DB.Table("orders").Joins("left join cars on cars.id=orders.cid").Select(
			"orders.order_no as OrderNo",
			"orders.from_address as FromAddress",
			"orders.to_address as ToAddress",
			"cars.car_code as CarCode",
			"cars.car_name as CarName",
			"cars.car_num as CarNum").Offset(offset).Limit(size).Find(&orders)
		cachedata, _ := json.Marshal(orders)
		cache.Rdb.Set(cache.Ctx, list_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &orders)
	}
	var total int64
	models.DB.Model(&models.Order{}).Count(&total)
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  orders,
		"total": total,
	})
	return
}
func OrderDetail(c *gin.Context) {
	id := c.Query("id")
	var order models.Order
	detail_key := "detail_key" + id
	cachejson, _ := cache.Rdb.Get(cache.Ctx, detail_key).Result()
	if cachejson == "" {
		models.DB.Where("id=?", id).First(&order)
		cachedata, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, detail_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &order)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	})
	return
}
